<!--
 搜索组件
 两种状态：仅展示和可输入，仅展示时引导用户点击前往搜索页，可输入即在搜索页搜索时
 @Author: mosowe
 @Date:2022-12-28 10:40:41
-->

<template>
  <view class="zo-search-bar">
    <view class="left-slot">
      <slot name="left"></slot>
    </view>
    <view
      class="content"
      @click="toSearchPage">
      <uni-easyinput
        prefixIcon="search"
        v-model="inputText"
        :placeholder="props.placeholder"
        placeholderStyle="color:#999;font-size:28rpx"
        clearable
        trim
        :focus="props.focus"
        :disabled="props.disabled"
        :inputBorder="false"
        confirmType="搜索"
        primaryColor="#c0c4cc"
        :styles="{
          color: '#3b3938',
          disableColor: 'none'
        }"></uni-easyinput>
    </view>
    <view
      v-if="showCancel"
      class="cancel"
      @click="backPage">
      取消
    </view>
    <view class="right-slot">
      <slot name="right"></slot>
    </view>
  </view>
</template>

<script setup lang="ts">
/* 
    slot: 
      left:左侧插槽
      right:右侧插槽
  */
import { ref, watchEffect } from 'vue';
// props定义
interface PropsType {
  modelValue?: string; // v-model值
  disabled?: boolean; // 搜索组件输入框是否禁用
  placeholder?: string; // 输入框提示语
  showCancel?: boolean; // 是否显示取消按钮
  searchUrl?: string; // 当组件只作为一个展示时，点击组件需要跳转的地址，通常是一个搜索页
  focus?: boolean;
}
const props = withDefaults(defineProps<PropsType>(), {
  modelValue: '',
  disabled: false,
  placeholder: '请输入搜索内容',
  showCancel: false,
  searchUrl: undefined,
  focus: false
});
// emits定义
interface emitsType {
  (e: 'update:modelValue', data: string): void;
}
const emits = defineEmits<emitsType>();

// 自定义组件v-model处理
const inputText = ref('');
watchEffect(() => {
  emits('update:modelValue', inputText.value);
});
watchEffect(() => {
  inputText.value = props.modelValue;
});

// 去搜索页，仅disabled为true，且searchUrl存在时
const toSearchPage = () => {
  if (props.disabled && props.searchUrl) {
    uni.navigateTo({
      url: props.searchUrl
    });
  }
};
// 取消
const backPage = () => {
  uni.navigateBack();
};
</script>

<style lang="scss" scoped>
.zo-search-bar {
  display: flex;
  height: 72rpx;
  line-height: 72rpx;
  .content {
    flex: 1;
    display: flex;
    background: #f7f8fc;
    border-radius: 16rpx;
    height: 100%;
    font-size: 28rpx;
    overflow: hidden;
  }
  .cancel {
    flex: none;
    font-weight: 400;
    font-size: 28rpx;
    color: #333333;
    margin-left: 30rpx;
  }
}
</style>
